<template>
  <a-dropdown placement="bottomRight">
    <template #overlay>
      <a-menu :selected-keys="[lang]" @click="switchLocale">
        <a-menu-item v-for="locale in locales" :key="locale">
          <span role="img" style="margin-right: 4px;" :aria-label="locale | languageLabels">
            {{ locale | languageIcons }}
          </span>
          {{ locale | languageLabels }}
        </a-menu-item>
      </a-menu>
    </template>
    <span class="ic-select-lang">
      <a-icon type="global" :title="$t('header.lang')" />
    </span>
  </a-dropdown>
</template>
<script lang="ts">
import { namespace } from 'vuex-class'
import { Vue, Component } from 'vue-property-decorator'

import { APP_LANGUAGE } from '@/enums/mutation-types'
import { LangType } from '~/locales'

const appSpace = namespace('app')
const languageLabels = {
  zh: '简体中文',
  en: 'English'
}
const languageIcons = {
  zh: '🇨🇳',
  en: '🇺🇸'
}

@Component({
  name: 'SelectLang',
  filters: {
    languageLabels (locale: string) {
      // @ts-ignore
      return languageLabels[locale]
    },
    languageIcons (locale: string) {
      // @ts-ignore
      return languageIcons[locale]
    }
  }
})
export default class SelectLang extends Vue {
  @appSpace.State('locales')
  locales!: string[]

  @appSpace.State('lang')
  lang!: LangType

  @appSpace.Mutation(APP_LANGUAGE)
  setLang!: (lang: LangType) => void

  switchLocale ({ key }: any) {
    this.$i18n.locale = key
    this.setLang(key)
    this.$cookies.set('lang', key)
  }
}
</script>
<style lang="less" scoped>
@import "~ant-design-vue/es/style/themes/default";
@header-menu-prefix-cls: ~'@{ant-prefix}-pro-header-menu';
.drop-down {
  line-height: @layout-header-height;
  vertical-align: top;
  cursor: pointer;
  > i {
    font-size: 16px !important;
    transform: none !important;
    svg {
      position: relative;
      top: -1px;
    }
  }
}
.ant-pro-select-lang {
  .ant-dropdown-menu-item {
    min-width: 160px;
  }
}
</style>
